﻿using System;
using System.Collections.Generic;
using System.Linq;
using Granite.DataAnnotations;
using System.ComponentModel.DataAnnotations;
using System.Xml.Linq;
using Granite.Modeling;

namespace BattleTech.Models
{
	public class EquipmentEntry : SimpleModelBase
	{
		public EquipmentEntry(Catalog catalog, XElement item)
		{
			switch (item.Name.LocalName)
			{
				case "Weapon":
					Equipment = catalog.GetWeapon(item.Attribute("Name").Value);
					break;
				case "Ammo":
					Equipment = catalog.GetAmmo(item.Attribute("Name").Value);
					break;
				default:
					throw new ArgumentException("Unknown item type: " + item.Name.LocalName);
			}
			Load(item.Attributes());
		}


		public EquipmentEntry(EquipmentDefinition equipment, Location location, decimal quantity)
		{
			if (equipment == null)
				throw new ArgumentNullException("equipment", "equipment is null.");
			
			Equipment = equipment;
			Location = location;
			Quantity = quantity;
		}

		public EquipmentDefinition Equipment
		{
			get { return Get<EquipmentDefinition>("Equipment"); }
			private set { Set(value, "Equipment"); }
		}

		public Location Location
		{
			get { return Get<Location>("Location"); }
			set { Set(value, "Location"); }
		}

		public decimal Quantity
		{
			get { return Get<decimal>(1, "Quantity"); }
			set { Set(value, "Quantity"); }
		}

		public int MaxQuantity
		{
			get
			{
				if (Equipment is WeaponDefinition)
					return 1;
				return (int)Math.Floor(100 / Equipment.Weight);
			}
		}

		[CalculatedField("Quantity")]
		public int Size
		{
			get { return (int)Math.Ceiling(Quantity * Equipment.Size); }
		}

		[CalculatedField("Quantity")]
		public decimal Weight
		{
			get { return Equipment.Weight * Quantity; }
		}

		protected override void OnValidateProperty(string propertyName, IList<ValidationResult> results)
		{
			base.OnValidateProperty(propertyName, results);

			if (string.IsNullOrEmpty(propertyName) || propertyName == "Quantity")
			{
				if (Quantity <= 0)
					results.Add(new ValidationResult("Quantity must be at least 1"));
				else if (Quantity > MaxQuantity)
					results.Add(new ValidationResult("Quantity cannot exceed " + MaxQuantity));
			}
		}
	}
}
